/**
 * 
 */
package cn.com.yinhex.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.activation.DataHandler;
import javax.activation.URLDataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ayou.util.FileUtil;
import ayou.util.StringUtil;

/**
 */
public class WgetUtil {

  protected static Log logger = LogFactory.getLog(WgetUtil.class);

  /**
   * ץȡ��ҳ����(����) �˷�������HTTP��FTPЭ��
   */
  public static String wgetDocument(String urlString) {
    return wgetDocument(urlString, "GBK");
  }

  /**
   * ץȡ��ҳ����(����) �˷�������HTTP��FTPЭ��
   */
  public static String wgetDocument(String urlString, String charset) {
    StringBuffer document = new StringBuffer();
    try {
      URL url = new URL(urlString);
      URLConnection conn = url.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn
          .getInputStream(), charset));
      String line = null;
      while ((line = reader.readLine()) != null) {
        document.append(line).append("\n");
      }
      reader.close();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return document.toString();
  }

  /**
   * ץȡ��ҳ����(���ı���������) �˷�������HTTP��FTPЭ��
   */
  public static String wgetTxt(String urlString) {
    StringBuffer document = new StringBuffer();
    try {
      URL url = new URL(urlString);
      URLConnection conn = url.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn
          .getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null) {
        document.append(line);
      }
      reader.close();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return document.toString();
  }

  /**
   * ץȡ�ļ�(ͼƬ��)���浽���� �˷���ֻ������HTTPЭ��
   */
  public static boolean wgetFile(String fileUrl, String fileName) {
    try {
      java.io.File file = new java.io.File(fileName);
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      // if (!file.exists()) {
      URL url = new URL(fileUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      DataInputStream in = new DataInputStream(connection.getInputStream());
      DataOutputStream out = new DataOutputStream(
          new FileOutputStream(fileName));
      byte[] buffer = new byte[4096];
      int count = 0;

      while ((count = in.read(buffer)) > 0) {
        out.write(buffer, 0, count);
      }
      out.close();
      in.close();
      // }
      return true;
    } catch (Exception e) {
      return false;
    }
  }

  /**
   * 
   * @param source
   */
  public static void buildHTML(String source, String dist) {
    if (!StringUtil.isFine(source) || !StringUtil.isFine(dist)) {
      return;
    }
    File target;
    String data;
    PrintWriter targetWriter = null;
    BufferedReader reader = null;
    String path = dist.substring(0,dist.lastIndexOf("/")+1);
    String name = dist.substring(dist.lastIndexOf("/")+1,dist.lastIndexOf("."));
    
    String bak = path + name + "_bak." + FileUtil.getFileType(dist);
    try {
      target = new File(bak);
      if (!target.getParentFile().exists()) {
        target.getParentFile().mkdirs();
      }
      target.createNewFile();
      targetWriter = new PrintWriter(target, "GBK");
      reader = new BufferedReader(new InputStreamReader(new DataHandler(
          new URLDataSource(new URL(source))).getInputStream(), "GBK"));
      while ((data = reader.readLine()) != null) {
        targetWriter.println(data);
      }
      targetWriter.flush();
      try {
        File file = new File(bak);
        if (file.exists() && file.length() > 1000) {
          FileUtil.copy(bak, dist, true);
          FileUtil.unlink(bak);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      logger.error("createHTML error:" + e.toString());
    } finally {
      try {
        targetWriter.close();
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        logger.error("createHTML error: close reader error!");
        targetWriter = null;
        reader = null;
      }
      target = null;
      targetWriter = null;
      reader = null;
    }
  }
}
